import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

// 通知项类型
interface NotificationItem {
  id: string;
  title: string;
  time: string;
  content: string;
  iconText: string;
  iconClass: string;
  url?: string;
  isRead?: boolean; // 添加已读状态
}

export const useNotificationStore = defineStore('notification', () => {
  const notificationList = ref<NotificationItem[]>([]);

  // 计算未读通知数量
  const unreadCount = computed(() => {
    return notificationList.value.filter(item => !item.isRead).length;
  });

  // 计算今日通知数量
  const todayCount = computed(() => {
    const today = new Date().toDateString();
    return notificationList.value.filter(item => {
      const itemDate = new Date(item.time).toDateString();
      return itemDate === today;
    }).length;
  });

  // 设置通知列表（带基础校验和默认值）
  const setNotificationList = (list: any[]) => {
    notificationList.value = list.map(item => ({
      id: item.id || '',
      title: item.title || '无标题',
      time: item.time || '',
      content: item.content || '',
      iconText: item.iconText || '!',
      iconClass: item.iconClass || 'alarm',
      url: item.url || '',
      isRead: item.isRead || false // 默认为未读
    }));
  };

  // 添加新通知
  const addNotification = (notification: any) => {
    const newNotification = {
      id: notification.id || Date.now().toString(),
      title: notification.title || '新通知',
      time: notification.time || '',
      content: notification.content || '',
      iconText: notification.iconText || '!',
      iconClass: notification.iconClass || 'alarm',
      url: notification.url || '',
      isRead: false // 新通知默认为未读
    };
    
    // 将新通知添加到列表开头
    notificationList.value.unshift(newNotification);
    
    // 限制通知数量，最多保留50条
    if (notificationList.value.length > 50) {
      notificationList.value = notificationList.value.slice(0, 50);
    }
  };

  // 处理WebSocket实时通知
  const handleRealtimeNotification = (data: any) => {
    try {
      // 验证数据格式
      if (!data || typeof data !== 'object') {
        console.error('通知数据格式错误:', data);
        return;
      }
      
      // 检查是否已存在相同ID的通知
      const existingIndex = notificationList.value.findIndex(item => item.id === data.id);
      
      if (existingIndex !== -1) {
        // 如果已存在，更新通知内容
        notificationList.value[existingIndex] = {
          ...notificationList.value[existingIndex],
          title: data.title || notificationList.value[existingIndex].title,
          content: data.content || notificationList.value[existingIndex].content,
          time: data.time || notificationList.value[existingIndex].time,
          iconClass: data.iconClass || notificationList.value[existingIndex].iconClass,
          url: data.url || notificationList.value[existingIndex].url
        };
      } else {
        // 如果不存在，添加新通知
        addNotification(data);
      }
    } catch (error) {
      console.error('处理实时通知时出错:', error);
    }
  };

  // 处理HTTP批量通知数据（APP启动时）
  const handleBatchNotifications = (data: any) => {
    try {
      // 验证数据格式
      if (!data || typeof data !== 'object') {
        console.error('批量通知数据格式错误:', data);
        return;
      }
      
      // 适配HTTP响应数据结构：data.list 或 data.notificationList.list
      const notificationListData = data.list || data.notificationList?.list;
      if (!notificationListData || !Array.isArray(notificationListData)) {
        console.error('批量通知数据中list字段不是数组:', data);
        return;
      }
      
      // 清空现有列表
      notificationList.value = [];
      
      // 添加批量通知
      notificationListData.forEach((notification: any, index: number) => {
        try {
          // 验证单个通知数据
          if (!notification || typeof notification !== 'object') {
            console.warn(`跳过无效的通知数据 [${index}]:`, notification);
            return;
          }
          
                     const formattedNotification = {
             id: notification.id || `notification-${Date.now()}-${index}`, // 如果没有id，使用时间戳+索引生成
             title: notification.title || '通知',
             time: notification.notifiedTime || new Date().toLocaleString(), // 使用 notifiedTime 字段
             content: notification.content || '',
             iconText: notification.iconText || '!',
             iconClass: notification.iconClass || 'alarm',
             url: notification.url || '',
             isRead: notification.isRead === 1 ? false : true // 后端返回 0=未读，1=已读，需要转换
           };
          
          notificationList.value.push(formattedNotification);
        } catch (error) {
          console.error(`处理通知数据 [${index}] 时出错:`, error, notification);
        }
      });
    } catch (error) {
      console.error('处理批量通知数据时出错:', error);
    }
  };

  // 标记通知为已读
  const markAsRead = async (id: string) => {
    const notification = notificationList.value.find(item => item.id === id);
    if (!notification) {
      console.warn(`通知 ${id} 不存在`);
      return false;
    }
    
    if (notification.isRead) {
      return true;
    }
    
    // 先更新本地状态
    notification.isRead = true;
    
    // 发送请求到后端标记为已读
    try {
      // 暂时注释掉真实API调用，直接使用模拟数据
      // await createRequest('/api/notifications/mark-read', {
      //   method: 'POST',
      //   data: { id },
      //   showLoading: false
      // });
      
      return true;
    } catch (error) {
      console.error('标记已读失败:', error);
      // 如果请求失败，回滚状态
      notification.isRead = false;
      return false;
    }
  };

  // 标记所有通知为已读
  const markAllAsRead = async () => {
    const unreadNotifications = notificationList.value.filter(item => !item.isRead);
    if (unreadNotifications.length === 0) {
      return true;
    }
    
    // 先更新本地状态
    unreadNotifications.forEach(item => {
      item.isRead = true;
    });
    
    try {
      // 暂时注释掉真实API调用，直接使用模拟数据
      // await createRequest('/api/notifications/mark-all-read', {
      //   method: 'POST',
      //   showLoading: false
      // });
      
      return true;
    } catch (error) {
      console.error('批量标记已读失败:', error);
      // 如果请求失败，回滚状态
      unreadNotifications.forEach(item => {
        item.isRead = false;
      });
      return false;
    }
  };

  // 删除通知
  const deleteNotification = (id: string) => {
    const index = notificationList.value.findIndex(item => item.id === id);
    if (index !== -1) {
      notificationList.value.splice(index, 1);
      return true;
    }
    return false;
  };

  // 清除已读通知
  const clearReadNotifications = () => {
    const readCount = notificationList.value.filter(item => item.isRead).length;
    notificationList.value = notificationList.value.filter(item => !item.isRead);
    return readCount;
  };

  // 清除通知列表
  const clearNotifications = () => {
    notificationList.value = [];
  };

  // 获取通知统计信息
  const getNotificationStats = () => {
    const total = notificationList.value.length;
    const unread = unreadCount.value;
    const read = total - unread;
    const today = todayCount.value;
    
    return {
      total,
      unread,
      read,
      today
    };
  };

  return {
    notificationList,
    unreadCount,
    todayCount,
    setNotificationList,
    addNotification,
    handleRealtimeNotification,
    handleBatchNotifications,
    markAsRead,
    markAllAsRead,
    deleteNotification,
    clearReadNotifications,
    clearNotifications,
    getNotificationStats
  };
});
